package com.zuihai.app.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.WindowManager;

import com.blankj.utilcode.util.LogUtils;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxUtils;
import com.zuihai.app.mvp.constant.MyConstant;
import com.zuihai.app.mvp.contract.HomeRecyclerContract;
import com.zuihai.app.mvp.model.entity.BaseJson;
import com.zuihai.app.mvp.model.entity.HomeBanner;
import com.zuihai.app.mvp.model.entity.HomeItem;
import com.zuihai.app.mvp.ui.adapter.HomeRecyclerAdapter;
import com.zuihai.app.mvp.ui.utils.AccountHelper;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/4 0004.
 */

@FragmentScope
public class HomeRecyclerPresenter extends BasePresenter<HomeRecyclerContract.Model, HomeRecyclerContract.View> {
    private RxErrorHandler mErrorHandler;
    private Application mApplication;
    private AppManager mAppManager;
    private List<HomeItem> mDatas = new ArrayList<>();

    private HomeRecyclerAdapter mAdapter;

    private int mPageIndex = 1;
    private List<HomeBanner> mBanners;

    @Inject
    public HomeRecyclerPresenter(HomeRecyclerContract.Model model, HomeRecyclerContract.View rootView
            , RxErrorHandler handler, Application application, AppManager appManager) {
        super(model, rootView);
        this.mErrorHandler = handler;
        this.mApplication = application;
        this.mAppManager = appManager;
        WindowManager wm = (WindowManager) application
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14+14+4+4, mApplication.getResources().getDisplayMetrics());

        mAdapter = new HomeRecyclerAdapter(mDatas,width-padding);

        mRootView.bindAdapter(mAdapter);

    }

    /**
     * 所有文章请求次接口
     * @param isRefresh
     */
    public void getActicle(boolean isRefresh,String type) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.getActicle(uid, mPageIndex,type)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    /**
     * 请求发现秘密
     * @param isRefresh
     */
    public void requestSecret(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestSecret( uid,mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestShopping(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestShopping(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }
    public void requestPeriphery(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestPeriphery(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }
    public void requestActivity(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestActivity(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestActical(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestActical(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestRecommend(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestRecommend(mPageIndex, uid)
                .zipWith(mModel.requestBanner(), new Func2<BaseJson<HomeItem>, BaseJson<HomeBanner>, BaseJson<HomeItem>>() {
                    @Override
                    public BaseJson<HomeItem> call(BaseJson<HomeItem> homeItem, BaseJson<HomeBanner> homeBanner) {
                        if (homeBanner.isSuccess()) {
                            mBanners = homeBanner.data.result;
                        }
                        return homeItem;
                    }
                })
                .compose(applySchedulers(isRefresh))
                .subscribe(new ErrorHandleSubscriber<List<HomeItem>>(mErrorHandler) {
                    @Override
                    public void onNext(List<HomeItem> homeItems) {
                        //填充广告轮播图
                        mRootView.fillBanner(mAdapter, mBanners);
                        mPageIndex++;
                        if (isRefresh) {
                            mAdapter.setNewData(homeItems);
                        } else {
                            if (homeItems.isEmpty()) {
                                mAdapter.loadMoreEnd();
                            } else {
                                mAdapter.addData(homeItems);
                                mAdapter.loadMoreComplete();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (!isRefresh) {
                            mAdapter.loadMoreFail();
                        } else {
                            mRootView.hideLoading();
                            if (e instanceof ConnectException) {
                                mRootView.showMessage("网络连接失败");
                            } else {
                                mRootView.showMessage("好像断网");
                            }
                        }
                        mRootView.handleError(e);
                    }
                });
    }

    public void requestPersion(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestPersion(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }
    public void requestHelp(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requesHelp(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestStory(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestStory(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }
    public void requestHeadline(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestHeadline(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestDiary(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestDiary(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestHot(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestHot(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }


    public void requestPicture(boolean isRefresh,String type) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestPicture( mPageIndex, uid,type)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }
    public void requestMyHeadline(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        String userID;
        if (TextUtils.isEmpty( MyConstant.HOMEPAGE_USERID)){
            userID=uid;
        }else {
            userID=MyConstant.HOMEPAGE_USERID;
        }
        LogUtils.e("userID : "+userID);

        mModel.requestMyHeadline(userID,uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .compose(RxUtils.bindToLifecycle(mRootView))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestFindRecomment(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestFindRecommend(mPageIndex, uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }


    public <T> Observable.Transformer<BaseJson<T>, List<T>> applySchedulers(boolean isRefresh) {
        return observable -> observable
                .retryWhen(new RetryWithDelay(3, 3))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(baseJson -> {
                    if (baseJson.isSuccess()) {
                        return baseJson.data.result;
                    }
                    return null;
                })
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        if (isRefresh) {
                            mRootView.hideLoading();
                        }
                    }
                })
                .compose(RxUtils.bindToLifecycle(mRootView));
    }

    @NonNull
    private ErrorHandleSubscriber<List<HomeItem>> getSubscriber(final boolean isRefresh) {
        return new ErrorHandleSubscriber<List<HomeItem>>(mErrorHandler) {
            @Override
            public void onNext(List<HomeItem> homeItems) {
                mPageIndex++;
                if (isRefresh) {
                    mAdapter.setNewData(homeItems);
                } else {
                    if (homeItems.isEmpty()) {
                        mAdapter.loadMoreEnd();
                    } else {
                        mAdapter.addData(homeItems);
                        mAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (!isRefresh) {
                    mAdapter.loadMoreFail();
                } else {
                    mRootView.hideLoading();
                    if (e instanceof ConnectException) {
                        mRootView.showMessage("网络连接失败");
                    } else {
                        mRootView.showMessage("好像断网");
                    }
                }
                mRootView.handleError(e);
            }
        };
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mApplication = null;
    }


}